/*
 * (C) 2014-2015 Alibaba Group Holding Limited
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 *
 *     __  ___   ______        ___       __          ___
 *    |  |/  /  /  __  \      /   \     |  |        /   \
 *    |  '  /  |  |  |  |    /  ^  \    |  |       /  ^  \
 *    |    <   |  |  |  |   /  /_\  \   |  |      /  /_\  \
 *    |  .  \  |  `--'  |  /  _____  \  |  `----./  _____  \
 *    |__|\__\  \______/  /__/     \__\ |_______/__/     \__\
 *
 *
 *
 */
//
// Created by KOALA TEAM on 12/19/14.
//

#import "UILabel+KLContentSize.h"

@implementation UILabel (KLContentSize)
- (CGSize)contentSize
{
    return [self contentSize:self.text];
}

- (CGSize)contentSize:(NSString*)text{
    CGSize frameSize = [self.superview bounds].size;
    CGSize maximumLabelSize =     CGSizeMake(frameSize.width,self.frame.size.height);
    return [self contentSize:text maxSize:maximumLabelSize];
}


- (CGSize)contentSize:(NSString*)text maxSize:(CGSize)maxSize{
    CGSize contentSize;
    if([[[UIDevice currentDevice]  systemVersion] floatValue]<= 7.0)
    {
        [self setLineBreakMode:NSLineBreakByWordWrapping];

        contentSize = [text sizeWithFont:[self font] constrainedToSize:maxSize lineBreakMode:[self lineBreakMode]];
    }
    else
    {
        NSDictionary * attributes = nil;
        if(text){
            NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
            paragraphStyle.lineBreakMode = self.lineBreakMode;
            paragraphStyle.alignment = self.textAlignment;
            attributes = @{NSFontAttributeName : self.font,
                    NSParagraphStyleAttributeName : paragraphStyle};
            contentSize = [text boundingRectWithSize:maxSize
                                             options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                          attributes:attributes
                                             context:nil].size;

        }else{
            contentSize = [self.attributedText boundingRectWithSize:maxSize options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                                            context:nil].size;
        }

    }
    return contentSize;
}

//ios6 later
-(CGSize)autoSize{
    if(self.text){
        return [self.text boundingRectWithSize:self.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.font} context:nil].size;
    }else{
        return [self.attributedText boundingRectWithSize:self.frame.size options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) context:nil].size;
    }
}
@end
